<template>
  <form @submit.prevent="handleSubmit" class="space-y-6">
    <!-- 基本信息 -->
    <div class="card">
      <h2 class="text-xl font-semibold mb-4">基本信息</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <UiInput
            v-model="form.title"
            type="text"
            label="电影标题"
            required
            placeholder="输入电影标题"
          />
        </div>
        <div>
          <UiInput
            v-model="form.originalTitle"
            type="text"
            label="原始标题"
            placeholder="输入原始标题（可选）"
          />
        </div>
        <div>
          <UiNumberInput
            v-model="form.year"
            label="年份"
            required
            :min="1900"
            :max="new Date().getFullYear()"
            placeholder="2024"
          />
        </div>
        <div>
          <UiInput
            v-model="form.duration"
            type="text"
            label="时长"
            required
            placeholder="例如：2小时30分钟"
          />
        </div>
        <div>
          <UiSelect
            v-model="form.universe"
            :options="availableUniverses"
            label="平行宇宙设定"
            placeholder="选择平行宇宙设定"
            searchable
          />
        </div>
        <div>
          <UiSelect
            v-model="form.language"
            :options="availableLanguages"
            label="语言"
            placeholder="选择语言"
            searchable
          />
        </div>
        <div>
          <UiSelect
            v-model="form.country"
            :options="availableCountries"
            label="国家/地区"
            placeholder="选择国家/地区"
            searchable
          />
        </div>
        <div>
          <UiNumberInput
            v-model="form.rating"
            label="评分"
            :min="0"
            :max="10"
            :step="0.1"
            placeholder="0.0-10.0"
          />
        </div>
        <div>
          <UiInput
            v-model="form.budget"
            type="text"
            label="预算"
            placeholder="例如：1000万平行币"
          />
        </div>
        <div>
          <UiInput
            v-model="form.box_office"
            type="text"
            label="票房"
            placeholder="例如：5000万平行币"
          />
        </div>
        <div>
          <label class="block text-sm font-medium mb-2">AI生成标识</label>
          <div class="flex items-center space-x-4">
            <UiRadio v-model="form.isAi" :value="false" label="人工创作" />
            <UiRadio v-model="form.isAi" :value="true" label="AI生成" />
          </div>
        </div>
      </div>
    </div>

    <!-- 类型标签 -->
    <div class="card">
      <h2 class="text-xl font-semibold mb-4">类型标签</h2>
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-2">电影类型 <span class="text-red-500">*</span></label>
          <div class="flex flex-wrap gap-2">
            <UiButton
              v-for="genre in availableGenres"
              :key="genre"
              @click="toggleGenre(genre)"
              :variant="form.genres.includes(genre) ? 'primary' : 'ghost'"
              size="sm"
            >
              {{ genre }}
            </UiButton>
          </div>
          <div v-if="showGenreError" class="text-red-500 text-sm mt-1">
            请至少选择一个电影类型
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium mb-2">自定义标签</label>
          <div class="flex gap-2">
            <UiInput v-model="newTag" placeholder="输入自定义标签" class="flex-1" />
            <UiButton @click="addTag" variant="secondary" size="sm"> 添加 </UiButton>
          </div>
          <div class="flex flex-wrap gap-2 mt-2">
            <UiBadge
              v-for="tag in form.tags"
              :key="tag"
              variant="secondary"
              class="cursor-pointer"
              @click="removeTag(tag)"
            >
              {{ tag }} ×
            </UiBadge>
          </div>
        </div>
      </div>
    </div>

    <!-- 创作团队 -->
    <div class="card">
      <h2 class="text-xl font-semibold mb-4">创作团队</h2>
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-2">导演 <span class="text-red-500">*</span></label>
          <div class="flex gap-2">
            <UiInput v-model="newDirector" placeholder="输入导演姓名" class="flex-1" />
            <UiButton @click="addDirector" variant="secondary" size="sm"> 添加 </UiButton>
          </div>
          <div class="flex flex-wrap gap-2 mt-2">
            <UiBadge
              v-for="director in form.directors"
              :key="director"
              variant="secondary"
              class="cursor-pointer"
              @click="removeDirector(director)"
            >
              {{ director }} ×
            </UiBadge>
          </div>
          <div v-if="showDirectorError" class="text-red-500 text-sm mt-1">
            请至少添加一个导演
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium mb-2">演员 <span class="text-red-500">*</span></label>
          <div class="flex gap-2">
            <UiInput v-model="newActor" placeholder="输入演员姓名" class="flex-1" />
            <UiButton @click="addActor" variant="secondary" size="sm"> 添加 </UiButton>
          </div>
          <div class="flex flex-wrap gap-2 mt-2">
            <UiBadge
              v-for="actor in form.actors"
              :key="actor"
              variant="secondary"
              class="cursor-pointer"
              @click="removeActor(actor)"
            >
              {{ actor }} ×
            </UiBadge>
          </div>
          <div v-if="showActorError" class="text-red-500 text-sm mt-1">
            请至少添加一个演员
          </div>
        </div>
      </div>
    </div>

    <!-- 内容描述 -->
    <div class="card">
      <h2 class="text-xl font-semibold mb-4">内容描述</h2>
      <div class="space-y-4">
        <div>
          <UiTextarea
            v-model="form.description"
            label="简介"
            required
            placeholder="简要描述电影内容"
            :rows="3"
          />
        </div>
        <div>
          <UiTextarea
            v-model="form.plot"
            label="剧情梗概"
            placeholder="详细描述电影剧情（可选）"
            :rows="5"
          />
        </div>
      </div>
    </div>

    <!-- 奖项与花絮 -->
    <div class="card">
      <h2 class="text-xl font-semibold mb-4">奖项与花絮</h2>
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-2">获奖情况</label>
          <div class="flex gap-2">
            <UiInput v-model="newAward" placeholder="输入奖项名称" class="flex-1" />
            <UiButton @click="addAward" variant="secondary" size="sm"> 添加 </UiButton>
          </div>
          <div class="flex flex-wrap gap-2 mt-2">
            <UiBadge
              v-for="award in form.awards"
              :key="award"
              variant="secondary"
              class="cursor-pointer"
              @click="removeAward(award)"
            >
              {{ award }} ×
            </UiBadge>
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium mb-2">幕后花絮</label>
          <div class="flex gap-2">
            <UiInput v-model="newTrivia" placeholder="输入花絮内容" class="flex-1" />
            <UiButton @click="addTrivia" variant="secondary" size="sm"> 添加 </UiButton>
          </div>
          <div class="flex flex-wrap gap-2 mt-2">
            <UiBadge
              v-for="trivia in form.trivia"
              :key="trivia"
              variant="secondary"
              class="cursor-pointer"
              @click="removeTrivia(trivia)"
            >
              {{ trivia }} ×
            </UiBadge>
          </div>
        </div>
      </div>
    </div>

    <!-- 封面图片 -->
    <div class="card">
      <h2 class="text-xl font-semibold mb-4">封面图片</h2>
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-2">封面图片 <span class="text-red-500">*</span></label>
          <ImageUpload
            :preview-url="coverPreview || originalCoverUrl"
            @file-selected="setCoverFile"
            @file-removed="removeCoverFile"
            @compression-complete="setCompressedCoverFile"
          />
          <div v-if="showCoverError" class="text-red-500 text-sm mt-1">
            请上传封面图片
          </div>
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="flex justify-end gap-4">
      <UiButton type="button" @click="handleReset" variant="secondary"> 重置 </UiButton>
      <UiButton type="button" @click="$emit('cancel')" variant="secondary"> 取消 </UiButton>
      <UiButton type="submit" :disabled="isLoading" variant="primary">
        {{ submitText }}
      </UiButton>
    </div>
  </form>
</template>

<script setup lang="ts">
  import { computed, ref, onMounted } from 'vue'
  import { storeToRefs } from 'pinia'
  import { useMovieStore } from '../../store/useMovieStore'
  import { useDraftStore } from '../../store/useDraftStore'
  import { useUiStore } from '../../store/useUiStore'
  import { watchDebounced } from '@vueuse/core'
  import {
    UiSelect,
    UiButton,
    UiInput,
    UiTextarea,
    UiRadio,
    UiBadge,
    ImageUpload,
    UiNumberInput,
  } from '../ui'

  // Props - 只保留必要的配置项
  interface Props {
    movieId?: number // 如果传入movieId，则为编辑模式
    submitText?: string // 提交按钮文本
  }

  const props = withDefaults(defineProps<Props>(), {
    submitText: '提交',
  })

  // 使用store
  const movieStore = useMovieStore()
  const draftStore = useDraftStore()
  const uiStore = useUiStore()

  // 错误状态
  const showGenreError = ref(false)
  const showDirectorError = ref(false)
  const showActorError = ref(false)
  const showCoverError = ref(false)

  // 从store中获取数据
  const {
    form,
    coverFile,
    coverPreview,
    originalCoverUrl,
    newTag,
    newDirector,
    newActor,
    newAward,
    newTrivia,
    availableGenres,
    availableUniverses,
    availableLanguages,
    availableCountries,
    isUploading,
    isUpdating,
  } = storeToRefs(movieStore)

  // 从store中获取方法
  const {
    toggleGenre,
    addTag,
    removeTag,
    addDirector,
    removeDirector,
    addActor,
    removeActor,
    addAward,
    removeAward,
    addTrivia,
    removeTrivia,
    setCoverFile,
    removeCoverFile,
    setCompressedCoverFile,
  } = movieStore

  // 计算属性
  const isLoading = computed(() => isUploading.value || isUpdating.value)

  // 验证表单
  const validateForm = () => {
    let isValid = true
    
    // 重置错误状态
    showGenreError.value = false
    showDirectorError.value = false
    showActorError.value = false
    showCoverError.value = false
    
    // 验证电影类型
    if (form.value.genres.length === 0) {
      showGenreError.value = true
      isValid = false
    }
    
    // 验证导演
    if (form.value.directors.length === 0) {
      showDirectorError.value = true
      isValid = false
    }
    
    // 验证演员
    if (form.value.actors.length === 0) {
      showActorError.value = true
      isValid = false
    }

    // 验证封面图片 - 在编辑模式下，如果有原始封面URL，则不需要新文件
    if (!coverFile.value && !originalCoverUrl.value) {
      showCoverError.value = true
      isValid = false
    }
    
    return isValid
  }

  // Emits - 只保留必要的事件
  const emit = defineEmits<{
    cancel: []
    submit: []
  }>()

  // 提交表单
  const handleSubmit = () => {
    if (validateForm()) {
      emit('submit')
    }
  }

  const handleReset = () => {
    movieStore.resetForm()
    if (props.movieId) {
      draftStore.clearEditDraft(props.movieId)
    } else {
      draftStore.clearUploadDraft()
    }
    uiStore.showSuccess('表单已重置，草稿已清除')
  }

  // ===== 草稿：恢复与自动保存 =====
  const EDIT_DRAFT_TTL_MS = 1000 * 60 * 60 * 24 * 7 // 7天

  onMounted(() => {
    try {
      if (props.movieId) {
        const draft = draftStore.getEditDraft(props.movieId)
        if (draft?.data) {
          // 深拷贝以确保 reactivity
          Object.assign(form.value, JSON.parse(JSON.stringify(draft.data.form)))
          if (draft.data.originalCoverUrl) originalCoverUrl.value = draft.data.originalCoverUrl
          if (draft.data.coverPreview) coverPreview.value = draft.data.coverPreview
          uiStore.showInfo('已从草稿恢复编辑内容')
        }
      } else {
        const draft = draftStore.getUploadDraft()
        if (draft?.data) {
          Object.assign(form.value, JSON.parse(JSON.stringify(draft.data.form)))
          if (draft.data.originalCoverUrl) originalCoverUrl.value = draft.data.originalCoverUrl
          if (draft.data.coverPreview) coverPreview.value = draft.data.coverPreview
          uiStore.showInfo('已从草稿恢复未提交内容')
        }
      }
    } catch (e) {
      // 忽略恢复异常
    }
  })

  watchDebounced(
    () => ({
      form: form.value,
      coverPreview: coverPreview.value,
      originalCoverUrl: originalCoverUrl.value,
    }),
    (snapshot) => {
      const payload = {
        form: { ...snapshot.form },
        coverPreview: snapshot.coverPreview,
        originalCoverUrl: snapshot.originalCoverUrl,
      }
      if (props.movieId) {
        draftStore.saveEditDraft(props.movieId, payload, EDIT_DRAFT_TTL_MS)
      } else {
        draftStore.saveUploadDraft(payload)
      }
    },
    { deep: true, debounce: 1500, maxWait: 5000 },
  )
</script>
